<template>
  <transition name="fade">
    <div class="modal-mask" v-show="visible" @click.self="close">
      <div class="modal-container">
        <div class="modal-header">
          <h3>用户登录</h3>
          <button class="modal-close" @click="close">×</button>
        </div>
        
        <div class="modal-body">
          <form class="auth-form" @submit.prevent="handleLogin">
            <div class="form-group">
              <input 
                type="text" 
                v-model="form.userTelno"
                placeholder="请输入手机号"
                required
              >
            </div>
            <div class="form-group">
              <input 
                type="password" 
                v-model="form.userPwd"
                placeholder="请输入密码"
                required
              >
            </div>
            <div class="form-options">
              <label>
                <input type="checkbox" v-model="form.remember"> 记住我
              </label>
              <a href="#" class="forgot-password">忘记密码?</a>
            </div>
            <button type="submit" class="auth-btn" :disabled="loading">
              {{ loading ? '登录中...' : '登录' }}
            </button>
            <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
          </form>

          <div class="auth-footer">
            <button class="auth-linksj" @click="handleMerchantLogin">我是商家</button>
            <div class="divider">或</div>
            <div class="social-login">
              <button class="social-btn wechat">
                <i class="icon-wechat"></i> 微信登录
              </button>
              <button class="social-btn qq">
                <i class="icon-qq"></i> QQ登录
              </button>
            </div>
            <p class="auth-link">
              还没有账号? <a href="#" @click.prevent="showRegister">立即注册</a>
            </p>
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/userStore'
import { userAPI } from '@/http'

const props = defineProps({
  visible: Boolean
})
const handleMerchantLogin = () => {
  close()
  router.push('/login2')
}
const emit = defineEmits(['update:visible', 'showRegister'])

const router = useRouter()
const userStore = useUserStore()

const form = ref({
  userTelno: '',
  userPwd: '',
  remember: false
})

const loading = ref(false)
const errorMessage = ref('')

const close = () => {
  errorMessage.value = ''
  emit('update:visible', false)
}

const showRegister = () => {
  close()
  emit('showRegister')
}

const handleLogin = async () => {
  // 验证输入
  if (!form.value.userTelno || !form.value.userPwd) {
    errorMessage.value = '请输入手机号和密码'
    return
  }

  loading.value = true
  errorMessage.value = ''

  try {
    const response = await userAPI.login({
      userTelno: form.value.userTelno,
      userPwd: form.value.userPwd
    })

    if (response.code === 200) {
      // 登录成功，保存用户信息和token
      const { userNickname, token, userImage } = response.data
      console.log(userNickname, token, userImage)
      console.log(userStore)
      
      // 保存到Pinia store
      userStore.setLoginInfo(userNickname, token, userImage)
      console.log("存入pinia store成功")
      // 记住我功能
      if (form.value.remember) {
        localStorage.setItem('rememberedUser', JSON.stringify({
          userTelno: form.value.userTelno
        }))
      } else {
        localStorage.removeItem('rememberedUser')
      }

      // 关闭登录框
      close()
      
      // 登录成功后刷新页面或跳转到首页
      // window.location.reload()
      // 或者使用路由跳转
      router.push('/')
    } else {
      errorMessage.value = response.message || '登录失败，请检查手机号和密码'
    }
  } catch (error) {
    console.error('登录出错:', error)
    errorMessage.value = '登录失败，请稍后再试'
  } finally {
    loading.value = false
  }
}

// 检查本地存储的记住我信息
const checkRememberedUser = () => {
  const rememberedUser = localStorage.getItem('rememberedUser')
  if (rememberedUser) {
    try {
      const user = JSON.parse(rememberedUser)
      form.value.userTelno = user.userTelno || ''
      form.value.remember = true
    } catch (e) {
      console.error('解析记住的用户信息失败:', e)
    }
  }
}

// 初始化时检查记住我
checkRememberedUser()
</script>
  
  <style scoped>
  .modal-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
  }
  
  .modal-container {
    width: 420px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    animation: modalIn 0.3s ease;
  }
  
  @keyframes modalIn {
    from {
      opacity: 0;
      transform: translateY(-20px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
  }
  
  .modal-header h3 {
    margin: 0;
    font-size: 18px;
    color: #333;
  }
  
  .modal-close {
    background: none;
    border: none;
    font-size: 24px;
    color: #999;
    cursor: pointer;
    padding: 0 10px;
    transition: color 0.3s;
  }
  
  .modal-close:hover {
    color: #ff6700;
  }
  
  .modal-body {
    padding: 20px;
  }
  
  /* 表单样式与之前相同 */
  .auth-form {
    margin-bottom: 20px;
  }
  
  .form-group {
    margin-bottom: 20px;
  }
  
  .form-group input {
    width: 90%;
    padding: 12px 15px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    font-size: 14px;
    transition: border 0.3s;
  }
  
  .form-group input:focus {
    border-color: #ff6700;
    outline: none;
  }
  
  .form-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    font-size: 14px;
    color: #666;
  }
  
  .forgot-password {
    color: #999;
    text-decoration: none;
    transition: color 0.3s;
  }
  
  .forgot-password:hover {
    color: #ff6700;
  }
  
  .auth-btn {
    width: 100%;
    padding: 12px;
    background: #ff6700;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    cursor: pointer;
    transition: background 0.3s;
  }
  
  .auth-btn:hover {
    background: #f25807;
  }
  
  .auth-footer {
    margin-top: 30px;
  }
  .auth-linksj {
    display: block;
    margin: 0 auto; /* 水平居中 */
    padding: 0px;
    color: rgb(12, 0, 0);
    border: none;
    border-radius: 2px;
    font-size: 12px;
    cursor: pointer;
    box-shadow: 0 4px 15px rgba(170, 191, 238, 0.3);
    transition: all 0.3s ease;
    width: fit-content; /* 自适应内容宽度 */
  }
  
  .divider {
    position: relative;
    margin: 20px 0;
    text-align: center;
    color: #ccc;
    font-size: 14px;
  }
  
  .divider::before,
  .divider::after {
    content: '';
    position: absolute;
    top: 50%;
    width: 30%;
    height: 1px;
    background: #f0f0f0;
  }
  
  .divider::before {
    left: 0;
  }
  
  .divider::after {
    right: 0;
  }
  
  .social-login {
    display: flex;
    gap: 15px;
    margin-bottom: 20px;
  }
  
  .social-btn {
    flex: 1;
    padding: 10px;
    border: 1px solid #f0f0f0;
    border-radius: 4px;
    background: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 5px;
    transition: all 0.3s;
  }
  
  .social-btn.wechat:hover {
    color: #09bb07;
    border-color: #09bb07;
  }
  
  .social-btn.qq:hover {
    color: #12b7f5;
    border-color: #12b7f5;
  }
  
  .icon-wechat,
  .icon-qq {
    font-style: normal;
    font-size: 18px;
  }
  
  .auth-link {
    text-align: center;
    color: #666;
    font-size: 14px;
  }
  
  .auth-link a {
    color: #ff6700;
    text-decoration: none;
  }
  
  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 0.3s;
  }
  
  .fade-enter-from,
  .fade-leave-to {
    opacity: 0;
  }
  .error-message {
  margin-top: 10px;
  color: #ff4d4f;
  font-size: 14px;
  text-align: center;
}

.auth-btn:disabled {
  background-color: #ffcccc;
  cursor: not-allowed;
}
  </style>